package com.ruoyi.framework.listener;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.io.resource.ResourceUtil;
import com.ruoyi.framework.config.properties.OpenVpnProperties;
import com.ruoyi.framework.config.properties.ServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.List;



/**
 * springboot程序启动后 创建认证的python文件 并修改server.conf , root路径下的*.ovpn文件
 */
@Component

public class BandwidthListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    ServerProperties serverProperties;

    @Autowired
    OpenVpnProperties openVpnProperties;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event)  {

        //windows 不执行初始化openvpn配置文件
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("windows")) {
            return;
        }


        //连接脚本输出路径
        String isOKPath = openVpnProperties.getIsOKPath();
        //断开脚本输出路径
        String disconnectPath = openVpnProperties.getDisconnectPath();

        //服务端配置文件路径
        String configPath = openVpnProperties.getConfigPath();

        //客户端文件根路径
        String clientOpenVpnPath = openVpnProperties.getClientOpenVpnPath();
        //获取本地的ip和端口

        String backendIP = serverProperties.getHost();
        Integer backendPort = serverProperties.getPort();
         /**
         Step1 添加py脚本
          */
        //读取resource下的模板文件
        String isOkContent = ResourceUtil.readUtf8Str("openvpn/isok.py");
        String disconnectContent = ResourceUtil.readUtf8Str("openvpn/disconnect.py");
        //替换当前ip和端口 写入文件
        FileUtil.writeUtf8String(isOkContent.replace("#{uri}", "http://"+backendIP+":"+backendPort),isOKPath);
        FileUtil.writeUtf8String(disconnectContent.replace("#{uri}", "http://"+backendIP+":"+backendPort),disconnectPath);

        /**
         * Step2 修改服务端配置文件并写入
         */

        File configFile = new File(configPath);
        String serverConf = FileUtil.readUtf8String(configFile);
        //判断是否需要修改
        if (!serverConf.contains("auth-user-pass-verify")) {
            StringBuilder newConfig = new StringBuilder(serverConf);
            // 追加换行符以避免和原内容粘连
            if (!serverConf.endsWith("\n")) {
                newConfig.append("\n");
            }
            newConfig.append("auth-user-pass-verify ").append(isOKPath).append(" via-env\n");
            newConfig.append("script-security 3\n");
            newConfig.append("username-as-common-name\n");
            newConfig.append("client-disconnect ").append(disconnectPath).append("\n");
            // 一次性写入文件
            FileUtil.writeUtf8String(newConfig.toString(), configFile);
        }

        /**
         * step3 修改根路径下的所有ovpn后缀文件添加
         */

        // 使用Hutool获取所有.ovpn文件
        // 获取所有.ovpn文件
        List<File> ovpnFiles = FileUtil.loopFiles(clientOpenVpnPath, path -> path.toString().endsWith(".ovpn"));
        for (File file : ovpnFiles) {
            // 读取文件内容
            List<String> lines = FileUtil.readUtf8Lines(file.toString());
            // 检查是否已经包含 auth-user-pass
            boolean hasAuthUserPass = lines.stream().anyMatch(line -> line.trim().startsWith("auth-user-pass"));
            if (hasAuthUserPass) {
                System.out.println("已包含 auth-user-pass，跳过文件: " + file);
                continue;
            }
            // 在verb 3的下一行添加auth-user-pass
            boolean modified = false;
            for (int i = 0; i < lines.size(); i++) {
                if (lines.get(i).trim().equals("verb 3")) {
                    lines.add(i + 1, "auth-user-pass");
                    modified = true;
                    break;
                }
            }
            // 如果文件被修改，则写入新内容
            if (modified) {
                FileWriter writer = new FileWriter(file.toString());
                writer.writeLines(lines);
            }
        }


        /**
         * step last
         * 赋予py文件 可执行 权限
         * 重启openvpn
         */
        try {
            System.out.println("修改初始环境配置");
            Runtime.getRuntime().exec("chmod 777 "+isOKPath);
            Runtime.getRuntime().exec("chmod 777 "+disconnectPath);
            Runtime.getRuntime().exec("systemctl restart openvpn-server@server.service");
            System.out.println("修改openvpn服务完成，已启动");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
